import { LoginForm, ProFormCheckbox, ProFormText } from '@ant-design/pro-components';
import { history, useModel, Helmet } from '@umijs/max';
import { Flex, Form } from 'antd';
import Settings from '../../../../config/defaultSettings';
import React, { useEffect, useState } from 'react';
import { flushSync } from 'react-dom';
import styles from './index.less';
import { getCaptchaCodeApi, login } from '@/services/user';
import storage, { GLOBAL_NAMESPACE } from '@/utils/storage';
import LoginIcon from '@/assets/images/login/logo.png';
import UserIcon from '@/assets/images/login/user.png';
import PassIcon from '@/assets/images/login/pass.png';
import CodeIcon from '@/assets/images/login/code.png';
import EyeIcon from '@/assets/images/login/eye.png';
import NoeyeIcon from '@/assets/images/login/no_eye.png';
import message from '@/utils/message';

const Login: React.FC = () => {
  const [form] = Form.useForm();
  const [captcha, setCaptcha] = useState({
    key: '',
    image: '',
  });
  const { initialState, setInitialState } = useModel('@@initialState');

  const getCaptchaCode = async () => {
    const { rsCode, body } = await getCaptchaCodeApi();
    if (rsCode === '00000000') {
      setCaptcha({
        key: body.uuid,
        image: body.captcha,
      });
    }
  };

  const fetchUserInfo = async (cb: () => void) => {
    const userInfo = await initialState?.fetchUserInfo?.();
    if (userInfo) {
      flushSync(() => {
        setInitialState((s) => ({
          ...s,
          currentUser: userInfo,
        }));
      });
      cb();
    }
  };

  const handleSubmit = async (values: API.LoginParams) => {
    try {
      // 登录
      const res = await login({
        ...values,
        uuid: captcha.key,
      });
      const { rsCode } = res;
      if (rsCode === '00000000') {
        storage.remove(GLOBAL_NAMESPACE, 'currentUser');
        storage.set(GLOBAL_NAMESPACE, 'currentUser', res.body);
        return fetchUserInfo(() => {
          message.success('登录成功');
          let url = '/home';
          history.replace(url);
        });
      }
      getCaptchaCode();
    } catch (error) {
      const defaultLoginFailureMessage = '登录失败，请重试！';
      message.error(defaultLoginFailureMessage);
      getCaptchaCode();
    }
  };

  useEffect(() => {
    getCaptchaCode();
  }, []);

  return (
    <div className={styles.container}>
      <Helmet>
        <title>登录页 - {Settings.title}</title>
      </Helmet>
      <div className={styles.login_form}>
        <LoginForm
          contentStyle={{
            minWidth: 280,
            maxWidth: '75vw',
            width: '95%',
          }}
          form={form}
          title={
            <Flex justify="center" align="center" className={styles.form_title} vertical gap={30}>
              <img src={LoginIcon} width={200} />
              用户登录
            </Flex>
          }
          subTitle=""
          onFinish={async (values) => {
            await handleSubmit(values as API.LoginParams);
          }}
        >
          <ProFormText
            name="phone"
            fieldProps={{
              size: 'large',
              prefix: <img src={UserIcon} width={16} height={16} />,
            }}
            placeholder="请输入用户名"
            rules={[
              {
                required: true,
                message: '请输入用户名',
              },
            ]}
          />
          <ProFormText.Password
            name="password"
            fieldProps={{
              size: 'large',
              prefix: <img src={PassIcon} width={16} height={16} />,
              iconRender: (v) => <img src={v ? EyeIcon : NoeyeIcon} width={18} height={18} />,
            }}
            placeholder="请输入密码"
            rules={[
              {
                required: true,
                message: '请输入密码',
              },
            ]}
          />
          <ProFormText
            name="code"
            fieldProps={{
              size: 'large',
              prefix: <img src={CodeIcon} width={16} height={16} />,
              suffix: <img height={32} width={100} src={captcha.image} onClick={getCaptchaCode} />,
              allowClear: false,
            }}
            placeholder="验证码"
            rules={[
              {
                required: true,
                message: '请输入验证码',
              },
            ]}
          />
        </LoginForm>
      </div>
    </div>
  );
};

export default Login;
